package com.navinfo.app.hd

import android.content.Context
import com.navinfo.collect.library.data.entity.GeometryFeatureEntity
import com.navinfo.collect.library.map.NIMapView
import com.navinfo.collect.library.map.layers.NIPolygonLayer
import com.navinfo.collect.library.utils.GeometryTools
import org.locationtech.jts.geom.LineString
import org.locationtech.jts.geom.Point
import org.locationtech.jts.geom.Polygon
import org.oscim.core.GeoPoint
import org.oscim.layers.marker.ItemizedLayer
import org.oscim.layers.marker.MarkerItem
import org.oscim.layers.vector.PathLayer
import org.oscim.map.Map

class HdItemDetailDisplay(mMap: Map, mContext: Context) {
    private val mMap: Map
    private val markerLayer: ItemizedLayer by lazy {ItemizedLayer(mMap, LayerStyle.getDefaultMarkerSymbol(mContext))}
    private val pathLayer: PathLayer by lazy {PathLayer(mMap, LayerStyle.getDefaultLineStyle())}
    private val polygonLayer: NIPolygonLayer by lazy {NIPolygonLayer(mMap, LayerStyle.getDefaultPolygonStyle())}

    init {
        this.mMap = mMap
    }

    private fun addHighLightHdLayer() {
        if (!mMap.layers().contains(markerLayer)) {
            mMap.layers().add(markerLayer, NIMapView.LAYER_GROUPS.OPERATE.groupIndex)
        }
        if (!mMap.layers().contains(pathLayer)) {
            mMap.layers().add(pathLayer, NIMapView.LAYER_GROUPS.OPERATE.groupIndex)
        }
        if (!mMap.layers().contains(polygonLayer)) {
            mMap.layers().add(polygonLayer, NIMapView.LAYER_GROUPS.OPERATE.groupIndex)
        }
    }

    fun clearHightLayer() {
        if (mMap.layers().contains(markerLayer)) {
            markerLayer.removeAllItems()
            markerLayer.update()
        }
        if (mMap.layers().contains(pathLayer)) {
            pathLayer.clearPath()
            pathLayer.update()
        }
        if (mMap.layers().contains(polygonLayer)) {
            polygonLayer.clearPath()
            polygonLayer.update()
        }
    }

    fun highLightHdItem(geometryEntity: GeometryFeatureEntity) {
        addHighLightHdLayer()
        clearHightLayer()
        // 高亮显示元素
        val geometry = GeometryTools.createGeometry(geometryEntity.geometry)
        if (geometry is Point) {
            val point = geometry as Point
            markerLayer.addItem(MarkerItem(geometryEntity, geometryEntity.name, geometryEntity.id, GeoPoint(point.y, point.x)))
            markerLayer.update()
        } else if (geometry is LineString) {
            pathLayer.setPoints(GeometryTools.getGeoPoints(geometryEntity.geometry))
            pathLayer.update()
        } else if (geometry is Polygon) {
            polygonLayer.setPoints(GeometryTools.getGeoPoints(geometryEntity.geometry))
            polygonLayer.update()
        }
        mMap.updateMap(true)
    }
}